package com.example.hello.filter;

import com.example.hello.util.CurrentHolder;
import com.example.hello.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1. 获取到请求的路径
        String path = request.getRequestURI();
        // 2. 判断是否是登录请求，如果是，直接放行  如果不是，返回401状态码
        if (path.contains("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 3. 获取到请求头中的token
        String token = request.getHeader("token");
        // 4. 判断token是否为空，为空则返回401状态码，不为空则继续执行
        if (token == null || token.isEmpty()){
            log.info("token为空");
            response.setStatus(401);
            return;
        }
        // 5. 解析token，如果解析失败则返回401状态码，如果解析成功则继续执行
        try {
            Claims claims = JwtUtils.parseJWT(token);
            // 将当前登录用户的id保存到ThreadLocal中
            Integer empId = (Integer) claims.get("id");
            CurrentHolder.setCurrentId(empId);
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(401);
            return;
        }
        // 6. 放行
        log.info("token解析成功,放行");
        filterChain.doFilter(servletRequest, servletResponse);

        // 7. 清除ThreadLocal中的数据
        CurrentHolder.remove();
    }
}